package com.baixiaowen.xiaoaointerview.并发提升篇.DelayQueue延迟队列;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayedQueueTest {

    static class DelayedItem<T> implements Delayed {

        T value;
        long time = 0;

        public DelayedItem(T value, long delay) {
            this.value = value;
            this.time = delay + System.currentTimeMillis();
        }

        /**
         * 返回延迟时间
         *
         *  延迟时间为0代表任务要执行
         *
         * @param unit
         * @return
         */
        @Override
        public long getDelay(TimeUnit unit) {
            return time - System.currentTimeMillis();
        }

        /**
         * 比较时间来决定优先级
         * @param o
         * @return
         */
        @Override
        public int compareTo(Delayed o) {
            return (int) (this.time - ((DelayedItem) o).time);
        }

        @Override
        public String toString() {
            return "DelayedInteger{" +
                    "value=" + value +
                    ", time=" + time +
                    '}';
        }
    }

    static DelayQueue<DelayedItem<Integer>> queue = new DelayQueue<>();

    public static void main(String[] args) {

        // Producer
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                // 非阻塞型生产
                queue.offer(new DelayedItem<Integer>(i, i * 1000));
            }
        }).start();

        // Consumer
        new Thread(() -> {
            while (true) {
                // 阻塞型消费
                try {
                    DelayedItem<Integer> item = queue.take();
                    System.err.println(item.toString());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
